package plenprojects.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

import plenprojects.exceptions.ImageManagerException;

public class ImageManager {
	
	private final String imageDirectory;
	
	public ImageManager(String imageDirectory) {
		
		this.imageDirectory = imageDirectory;
	}
	
	public void saveImage(byte[] bytes, String filename) throws ImageManagerException {
		
		if(this.findImage(filename) != null) {
			
			throw new ImageManagerException(String.format("File %s exists.", filename));
		}
		
		try {
			
			FileOutputStream stream = new FileOutputStream(imageDirectory + filename + ".jpg");
			stream.write(bytes);
			
			try {
				
				stream.close();
			}
			catch(IOException e) {
				
			}
			
		}
		catch(Exception e) {
			
			throw new ImageManagerException("Error while saving the image.");
		}
		
	}
	
	public File findImage(String name) {
		
		File dir = new File(imageDirectory);
		
		for(File file : dir.listFiles()) {
			
			if(file.getName().startsWith(name)) {
				
				return file;
			}
		}
		
		return null;
	}
	
	public byte[] getAllBytes(File file) throws IOException {
		
		return Files.readAllBytes(Paths.get(file.getAbsolutePath()));
	}
}
